import React from 'react';
import moment from 'moment';
import { connect } from 'dva';
import {
  Card,
  Form,
  Divider,
  Col,
  Row,
  DatePicker,
  Select,
  Tag,
  Input,
  Button,
  Modal,
  message,
} from 'antd';
import StandardTable from '@/components/StandardTable';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import AuthorizedButton from '@/components/AuthorizedButton';
import ReissueCouponForm from './component/ReissueCouponForm';

import styles from '../../styles/Manage.less';

const FormItem = Form.Item;
const { Option } = Select;

const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');

// 2天后的日期
const currentDate = moment(new Date(new Date().getTime()));

@Form.create()
@connect(({ marketCoupon, loading }) => ({
  marketCoupon,
  loading: loading.models.marketCoupon,
}))
class CouponManage extends React.Component {
  state = {
    date: currentDate, // 被预测时间
    dateString: currentDate.format('YYYY-MM-DD'),
    cities: [],
    cityId: '-1', // 城市ID
    appUserId: '',
    phone: '',
  };

  // 表格字段
  columns = [
    {
      title: '日期',
      width: 160,
      fixed: 'left',
      align: 'center',
      render: (text, record) => <span>{record.date}</span>,
    },
    { title: '城市', width: 120, dataIndex: 'cityId' },
    { title: '优惠券ID', width: 120, dataIndex: 'couponId' },
    { title: '用户ID', width: 120, dataIndex: 'appUserId' },
    { title: '电话号码', width: 120, dataIndex: 'phone' },
    {
      title: '状态',
      width: 120,
      dataIndex: 'status',
      align: 'center',
      render: text => {
        if (text === 0) return <Tag color="#108ee9">券发送</Tag>;
        if (text === 1) return <Tag color="#2db7f5">券触达</Tag>;
        return <Tag color="#f50">已发短信</Tag>;
      },
    },
    {
      title: '创建时间',
      width: 90,
      fixed: 'right',
      dataIndex: 'created',
      render: text => <span>{moment.unix(text).format('HH:mm')}</span>,
    },
  ];

  componentDidMount() {
    this.handleSearch();
    this.getCities();
  }

  getCities = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'commonInfo/fetchByClassify',
      payload: {
        classify: 'city',
      },
      callback: data => {
        const list = [];
        data.forEach(item => {
          list.push({
            code: item.code,
            name: item.name,
          });
        });
        this.setState({
          cities: list,
        });
      },
    });
  };

  getQueryParams = () => {
    const { dateString, cityId, appUserId, phone } = this.state;
    const params = {};

    if (cityId !== '-1') {
      params.cityId = cityId;
    }
    if (appUserId) {
      params.appUserId = appUserId;
    }
    if (phone) {
      params.phone = phone;
    }
    if (dateString) {
      params.date = dateString;
    }
    return params;
  };

  // 查询操作
  handleSearch = () => {
    const { dispatch } = this.props;
    const params = this.getQueryParams();
    dispatch({
      type: 'marketCoupon/fetch',
      payload: {
        params,
      },
      callback: () => {},
    });
  };

  // 补发券
  reissueCoupon = params => {
    const { dispatch } = this.props;
    dispatch({
      type: 'marketCoupon/reissueCoupon',
      payload: {
        ...params,
      },
      callback: data => {
        console.log(data);
        this.setState({
          modalVisible: false,
        });
        this.handleSearch();
      },
    });
  };

  // 分页、过滤、排序处理
  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;
    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    const queryParams = this.getQueryParams();

    const params = {
      ...formValues,
      ...filters,
      ...queryParams,
    };
    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }
    dispatch({
      type: 'marketCoupon/fetch',
      payload: {
        params,
        currentPage: pagination.current,
        pageSize: pagination.pageSize,
      },
    });
  };

  render() {
    const {
      loading,
      form: { getFieldDecorator },
      marketCoupon: { data },
    } = this.props;
    const { cityId, date, cities, modalVisible } = this.state;

    let totalWidth = 0;
    this.columns.forEach(col => {
      const { width } = col;
      if (width) {
        totalWidth += width;
      }
    });

    return (
      <PageHeaderWrapper title="智能优惠券" content="动态计算发券处理">
        <Card bordered={false}>
          <div className={styles.Manage}>
            <div className={styles.ManageForm}>
              <Form layout="inline">
                <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
                  <Col md={8} sm={24}>
                    <FormItem key="date" label="日期">
                      {getFieldDecorator('date', {
                        initialValue: date,
                      })(
                        <DatePicker
                          onChange={(dateNew, dateString) => {
                            this.setState(
                              {
                                date: dateNew,
                                dateString,
                              },
                              () => {
                                this.handleSearch();
                              }
                            );
                          }}
                          placeholder="选择日期"
                        />
                      )}
                    </FormItem>
                  </Col>
                  <Col md={8} sm={24}>
                    <FormItem key="cityId" label="城市ID">
                      {getFieldDecorator('cityId', {
                        initialValue: cityId,
                      })(
                        <Select
                          key="cityId"
                          placeholder="请选择城市"
                          showSearch
                          optionFilterProp="children"
                          onChange={value => {
                            this.setState(
                              {
                                cityId: value,
                              },
                              () => {
                                this.handleSearch();
                              }
                            );
                          }}
                        >
                          {cities.map(item => (
                            <Option key={item.code} value={item.code}>
                              {item.name}({item.code})
                            </Option>
                          ))}
                        </Select>
                      )}
                    </FormItem>
                  </Col>
                  <Col md={8} sm={24}>
                    <FormItem key="appUserId" label="用户ID">
                      {getFieldDecorator('appUserId', {})(
                        <Input
                          placeholder="请输入"
                          onChange={e => {
                            this.setState(
                              {
                                appUserId: e.target.value,
                              },
                              () => {
                                this.handleSearch();
                              }
                            );
                          }}
                        />
                      )}
                    </FormItem>
                  </Col>
                  <Col md={8} sm={24}>
                    <FormItem key="phone" label="手机号">
                      {getFieldDecorator('phone', {})(
                        <Input
                          placeholder="请输入"
                          onChange={e => {
                            this.setState(
                              {
                                phone: e.target.value,
                              },
                              () => {
                                this.handleSearch();
                              }
                            );
                          }}
                        />
                      )}
                    </FormItem>
                  </Col>
                </Row>
              </Form>
            </div>
            <div style={{ float: 'right', paddingBottom: '5px' }}>
              <AuthorizedButton mask={['ADD']}>
                <Button
                  type="primary"
                  onClick={() => {
                    const { dispatch } = this.props;
                    Modal.confirm({
                      title: '询问',
                      content: '确定手动发放今日优惠券么？',
                      okText: '确定',
                      cancelText: '再想想',
                      onOk: () => {
                        dispatch({
                          type: 'marketCoupon/dispatchCoupon',
                          payload: {},
                          callback: () => {
                            message.success('手动发券成功');
                          },
                        });
                      },
                    });
                  }}
                >
                  手动发放今日优惠券
                </Button>
                &nbsp;
                <Button
                  type="primary"
                  onClick={() => {
                    this.setState({
                      modalVisible: true,
                    });
                  }}
                >
                  补发放今日优惠券
                </Button>
              </AuthorizedButton>
            </div>
            <Divider type="horizontal" />
            <StandardTable
              loading={loading}
              data={data}
              scroll={{ x: totalWidth }}
              columns={this.columns}
              rowKey={record => record.id}
              onChange={this.handleStandardTableChange}
            />
          </div>
        </Card>
        {modalVisible && (
          <ReissueCouponForm
            modalVisible={modalVisible}
            handleOpt={this.reissueCoupon}
            handleModalVisible={() => {
              this.setState({
                modalVisible: false,
              });
            }}
          />
        )}
      </PageHeaderWrapper>
    );
  }
}

export default CouponManage;
